package main

import (
	"encoding/json"
	"fmt"
)

type OrderItem struct {
	ID    string  `json:"id"`
	Name  string  `json:"name"`
	Price float64 `json:"price"`
}

type Order struct { //tag
	ID         string       `json:"id"`
	Name       string       `json:"name,omitempty"` //省略空
	Quantity   int          `json:"quantity"`
	TotalPrice float64      `json:"total_price"`
	Items      []*OrderItem `json:"items"`
}

func main() {

	o := Order{
		ID: "1234",
		//Name:       "learn go",
		Quantity:   3,
		TotalPrice: 30,
		Items: []*OrderItem{{
			ID:    "item_1",
			Name:  "item_name_1",
			Price: 15,
		},
			{
				ID:    "item_2",
				Name:  "item_name_2",
				Price: 25,
			}},
	}

	b, err := json.Marshal(o)

	if err != nil {
		panic(err)
	}

	fmt.Printf("%s\n", b)

	unmarshal()

	parseNLP()
}

func unmarshal() {

	s := `{"id":"1234","quantity":3,"total_price":30,
"items":[{"id":"item_1","name":"item_name_1","price":15},
{"id":"item_2","name":"item_name_2","price":25}]}
`
	var o Order
	err := json.Unmarshal([]byte(s), &o)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%+v\n", o)
}

func parseNLP() {
	res := `{"data":[{"id":"0","word":"阿里巴巴","tags":["机构-机构半称","产品-品牌"]},{"id":"1","word":"集团","tags":["基本词-中文","产品类型修饰词"]},{"id":"2","word":"的","tags":["基本词-中文","文体娱乐类-flash作品"]},{"id":"3","word":"使命","tags":["基本词-中文","文体娱乐类-书文课程类","软件-纯软件名","产品类型修饰词"]},{"id":"4","word":"是","tags":["基本词-中文","文体娱乐类-flash作品"]},{"id":"5","word":"让","tags":["基本词-中文","文体娱乐类-flash作品"]},{"id":"6","word":"天下","tags":["产品-品牌","基本词-中文","软件-纯软件名"]},{"id":"7","word":"没有","tags":["基本词-中文","产品类型修饰词"]},{"id":"8","word":"难做","tags":["人民日报词汇"]},{"id":"9","word":"的","tags":["基本词-中文","文体娱乐类-flash作品"]},{"id":"10","word":"生意","tags":["基本词-中文","网站-其他","文体娱乐类-书文课程类","文体娱乐类-报纸杂志类","文体娱乐类-戏剧歌曲类","机构-机构特指"]},{"id":"11","word":"。","tags":[]}]}`

	m := make(map[string]interface{})
	err := json.Unmarshal([]byte(res), &m)
	if err != nil {
		panic(err)
	}
	//type assertion
	fmt.Println(m["data"].([]interface{})[2].(map[string]interface{})["word"])

	m2 := struct {
		Data []struct {
			Word string `json:"word"`
		} `json:"data"`
	}{}
	err = json.Unmarshal([]byte(res), &m2)
	if err != nil {
		panic(err)
	}
	//type assertion
	fmt.Println(m2)

}
